package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.views.MaxLengthWatcher;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.ProductAddEntity;
import com.epfresh.supplier.entity.TagPackage;
import com.epfresh.supplier.view.tag.FlowLayout;
import com.epfresh.supplier.view.tag.TagAdapter;
import com.epfresh.supplier.view.tag.TagFlowLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ProductAddCategoryVarietiesActivity extends BaseActivity {


    private EditText ed;
    private TextView tvAdd;

    private TagFlowLayout tagFlowLayout;


    private List<String> list = new ArrayList<>();

    private TagAdapter<String> tagAdapter;

    int tagW = -1;

    private String nameId = "";


    private String varietyName = "";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_add_category_varieties);


        if (savedInstanceState != null) {
            getIntent().putExtra("nameId", savedInstanceState.getString("nameId"));
            getIntent().putExtra("varietyName", savedInstanceState.getString("varietyName"));
            getIntent().putExtra("tagPackage", savedInstanceState.getString("tagPackage"));
            getIntent().putExtra("dataProduct", savedInstanceState.getString("dataProduct"));
            String dataProduct = getIntent().getStringExtra("dataProduct");
            if(dataProduct != null && !"".equals(dataProduct)) {
                DataManager.getInstance().setProductAddEntity(new Gson().fromJson(dataProduct,ProductAddEntity.class));
            }
        }

        varietyName = getIntent().getStringExtra("varietyName");
        initAddView();
        initView();
    }
    @Override
    protected void onToolbarBack() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
        super.onToolbarBack();
    }

    @Override
    public void onBackPressed() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
        super.onBackPressed();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("nameId", nameId);
        outState.putString("varietyName", varietyName);
        outState.putString("tagPackage", getIntent().getStringExtra("tagPackage"));
        ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();
        if(productAddEntity != null) {
            outState.putString("dataProduct", new Gson().toJson(productAddEntity));
        }
        super.onSaveInstanceState(outState);
    }


    protected void initAddView() {
        toolbarTitle.setText("品种");
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);

        View view = findViewById(R.id.ly_add);
        ed = (EditText) view.findViewById(R.id.et_add_content);
        tvAdd = (TextView) view.findViewById(R.id.tv_add_search);

        tvAdd.setText("清空");
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
                finish();
            }
        });
        ed.setHint("请添加新品种");

        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ed.setText("");
//                String vn = ed.getText().toString();
//                if (vn == null || "".equals(vn)) {
//                    toast("请添加新品种");
//                    return;
//                }
//                varietyName = vn;
//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
//
//                Set<Integer> set = new HashSet<Integer>();
//                tagAdapter.setSelectedList(set);
//                intoNext();
//                Intent intent = new Intent();
//                intent.putExtra("varietyName", varietyName);
//                setResult(RESULT_OK, intent);
//                finish();
            }
        });
        ed.addTextChangedListener(new MaxLengthWatcher(12, ed));

    }
    private TextView tvPre;
    private TextView tvNext;

    private void initNextView(){
        tvNext = (TextView) findViewById(R.id.tv_next);
        tvPre = (TextView) findViewById(R.id.tv_pre);

        tvPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                preView();
            }
        });
        tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                intoNext();
            }
        });
    }

    private void intoNext() {
//        if (varietyName == null || "".equals(varietyName)) {
//            toast("请添加新品种");
//            return;
//        }
//        requestTagList();
        nextView();
    }

    private void preView() {
        finish();
    }

    private void nextView() {

        ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();

        productAddEntity.setVarietyId(null);
        varietyName = ed.getText().toString();
        productAddEntity.setVariety(varietyName);

//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
        Intent intent = new Intent(this, ProductPackageActivity.class);


//        intent.putExtra("unit", productAddEntity.getPackageUnit());
//        intent.putExtra("packageSize", productAddEntity.getPackageSize());
//        intent.putExtra("container", productAddEntity.getPackageContainer());
//        intent.putExtra("weight", productAddEntity.getWeight());
        intent.putExtra("tagPackage", getIntent().getStringExtra("tagPackage"));
//        Log.e("weight", "1----" + productAddEntity.getWeight());
        startActivityForResult(intent, 0x49);
    }


//    public void test() {
//        List<String> list = new ArrayList<>();
//        list.add("尼泊尔1");
//        list.add("尼泊尔2");
//        list.add("尼泊尔3");
//        updateTag(list);
//    }

    private void initView() {

        initNextView();
        tagW = LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(46) ;
        tagW /= 3;

        tagFlowLayout = (TagFlowLayout) findViewById(R.id.t_tag);

        tagFlowLayout.setMaxSelectCount(1);
        tagAdapter = new TagAdapter<String>(list) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(ProductAddCategoryVarietiesActivity.this).inflate(R.layout.product_add_tag,
                        parent, false);
                ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) tv.getLayoutParams();
                lp.width = tagW;
//                if (position %3 == 0){
////                    lp.leftMargin = LocalDisplay.dp2px(15);
//                }else {
////                    lp.leftMargin = LocalDisplay.dp2px(8);
//                }

//                lp.rightMargin = 0;
//                lp.topMargin = LocalDisplay.dp2px(4);
//                lp.bottomMargin = LocalDisplay.dp2px(4);
                tv.setText(s);
                return tv;
            }
        };
        tagFlowLayout.setAdapter(tagAdapter);

        tagFlowLayout.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {

                if (selectPosSet != null && selectPosSet.size() > 0) {
                    for (Integer i : selectPosSet) {
                        if(i < list.size()) {
                            varietyName = list.get(i);
                            ed.setText(varietyName);
                            ed.setSelection(ed.length());
                        }
                    }

                    tagAdapter.setSelectedList(new HashSet<Integer>());
                }else {
                    ed.setText("");
                }
            }
        });
//        tagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
//            @Override
//            public boolean onTagClick(View view, int position, FlowLayout parent) {
//                if (position < list.size()) {
////                    tagAdapter.setSelectedList(position);
//
//                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                    imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
//                    varietyName = list.get(position);
//                    ed.setText(varietyName);
////                    Intent intent = new Intent();
////                    intent.putExtra("varietyName", varietyName);
////                    setResult(RESULT_OK, intent);
////                    finish();
//
////                    intoNext();
//                }
//                return true;
//            }
//        } );

//        test();

        nameId = getIntent().getStringExtra("nameId");
        requestCategory(nameId);
    }




    public void updateTag(List<String> list) {
        this.list.clear();
        if (list != null) {
            this.list.addAll(list);
        }
        tagAdapter.notifyDataChanged();

        for (int i = 0; i < this.list.size(); i++) {
            String s = this.list.get(i);
            if (s != null && !"".equals(s)&& s.equals(varietyName)){
                tagAdapter.setSelectedList(i);
            }
        }
    }


    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_btn:

                break;
        }
    }

    public void requestCategory(String nameId) {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_category_getMore);
        RequestEntityMapSupply.putParameter("nameId", nameId);
        RequestEntityMapSupply.putParameter("variety", "");
        RequestEntityMapSupply.putParameter("field", "variety");
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_category_getMore, onCategoryTreeRequestListener);

    }


    private OnRequestListener<List<String>> onCategoryTreeRequestListener = new OnRequestListener<List<String>>() {
        @Override
        public List<String> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<String>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<List<String>> response, Object tag) {


            List<String> responseElement = response.getResponseElement();

            if (responseElement != null && responseElement.size() > 0) {

                updateTag(responseElement);

            }
        }
    };
}
